<?php
Zend_Loader::loadClass("LogLine");

/**
 * @author Tuan Ngo
 *
 */
class LogModel {
	
	private $log_texts;
	private $log_line;
	private $log_file_name;
	private $log_file_path;
	
	public function LogModel(){
		$this->log_texts = array();
		$this->log_line = new LogLine(NULL);	
		$this->log_file_name = date("Y-m-d") . ".log";
		$this->log_file_path = LOG_PATH . "/" . $this->log_file_name;
		
		$this->cleanOldLog();
	}
	
	public function flush(){
		$logFile = fopen($this->log_file_path, "a+");
		
		//flush all log texts to file
		foreach ($this->log_texts as $text){
			fwrite($logFile, $text . "\n");	
		}
		
		fclose($logFile);
	}
	
	public function cleanOldLog(){
		//get oldest accept file name
		$cur_date = date("Y-m-j");
		$log_store_month = LOG_STORE_TIME;
		$remove_from = strtotime ("-$log_store_month month", strtotime($cur_date)) ;
		$remove_from = date("Y-m-j", $remove_from) . ".log";
		
		//scan list file to delete
		$remove_file_arr = array();
		$handle = opendir(LOG_PATH);
		if ($handle) {
		    while (false !== ($entry = readdir($handle))) {
		        if ($entry != "." && $entry != "..") {
		            if($entry < $remove_from)
		            	$remove_file_arr[] = $entry;
		        }
		    }
		    closedir($handle);
		}
		
		//delete file
		foreach ($remove_file_arr as $file){
			unlink(LOG_PATH . "/" . $file);
		}
	}
	
	public function addLogLine($log_line){
		$this->log_texts[] = $log_line->getText();
	}
	
	public function getLogTexts() {
		return $this->log_texts;
	}
	
	public function getLogFileName() {
		return $this->log_file_name;
	}

	public function setLogFileName($log_file_name) {
		$this->log_file_name = $log_file_name;
	}

	public function getLogLine() {
		return $this->log_line;
	}

	public function setLogTexts($log_texts) {
		$this->log_texts = $log_texts;
	}

	public function setLogLine($log_line) {
		$this->log_line = $log_line;
	}
}
?>